"""
MCP工具模块
提供LangChain工具来调用MCP服务
"""

from typing import Dict, Any, Optional, List
from langchain.tools import BaseTool
from src.services.mcp_service import mcp_service_manager, MCPServiceError
from src.config.settings import settings
import json


class MCPTool(BaseTool):
    """MCP工具类，用于调用MCP服务器上的工具"""
    
    name: str = "mcp_tool"
    description: str = "调用MCP服务器上的工具"
    
    def _run(self, server: str, tool: str, parameters: Dict[str, Any]) -> str:
        """
        同步运行MCP工具
        
        Args:
            server: MCP服务器名称
            tool: 工具名称
            parameters: 工具参数
            
        Returns:
            工具调用结果的JSON字符串
        """
        try:
            result = mcp_service_manager.call_tool_sync(server, tool, parameters)
            return json.dumps(result, ensure_ascii=False)
        except MCPServiceError as e:
            return f"调用MCP工具失败: {str(e)}"
        except Exception as e:
            return f"意外错误: {str(e)}"
    
    async def _arun(self, server: str, tool: str, parameters: Dict[str, Any]) -> str:
        """
        异步运行MCP工具
        
        Args:
            server: MCP服务器名称
            tool: 工具名称
            parameters: 工具参数
            
        Returns:
            工具调用结果的JSON字符串
        """
        try:
            result = await mcp_service_manager.call_tool_async(server, tool, parameters)
            return json.dumps(result, ensure_ascii=False)
        except MCPServiceError as e:
            return f"调用MCP工具失败: {str(e)}"
        except Exception as e:
            return f"意外错误: {str(e)}"


def get_mcp_tool() -> BaseTool:
    """
    获取MCP工具实例
    
    Returns:
        MCPTool实例
    """
    return MCPTool()


def get_available_mcp_tools(server_name: str) -> List[str]:
    """
    获取指定MCP服务器上可用的工具列表
    
    Args:
        server_name: MCP服务器名称
        
    Returns:
        工具名称列表
    """
    try:
        return mcp_service_manager.list_tools(server_name)
    except Exception as e:
        print(f"获取MCP工具列表失败: {e}")
        return []


def is_mcp_server_available(server_name: str) -> bool:
    """
    检查MCP服务器是否可用
    
    Args:
        server_name: MCP服务器名称
        
    Returns:
        服务器是否可用
    """
    return mcp_service_manager.is_server_available(server_name)


def get_mcp_server_config(server_name: str) -> Dict[str, Any]:
    """
    获取MCP服务器配置
    
    Args:
        server_name: MCP服务器名称
        
    Returns:
        服务器配置字典
    """
    return mcp_service_manager.get_server_config(server_name)


def get_all_mcp_servers() -> Dict[str, Any]:
    """
    获取所有MCP服务器信息
    
    Returns:
        包含启用状态、服务器列表和配置的字典
    """
    return {
        "enabled": settings.MCP_ENABLED,
        "servers": settings.MCP_SERVERS,
        "server_configs": settings.MCP_SERVER_CONFIGS
    }